package com.school.sports.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.school.sports.dto.UserDTO;
import com.school.sports.entity.LoginInfo;
import com.school.sports.entity.User;
import com.school.sports.mapper.UserMapper;
import com.school.sports.service.UserService;
import com.school.sports.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean register(User user) {
        // 1. 校验用户名是否已存在
        if (checkUsernameExists(user.getUsername())) {
            return false;
        }

        // 2. 密码加密
        user.setPasswordHash(passwordEncoder.encode(user.getPasswordHash()));

        // 3. 设置默认值
        user.setIsActive(true);
        user.setRoleId(4); // 默认为学生角色
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        // 4. 保存用户
        return userMapper.insert(user) > 0;
    }

    @Override
    public LoginInfo login(User user) {
        //1.调用mapper接口，根据用户名查询员工信息
        User u = userMapper.findByUsername(user.getUsername());

        //2.判断:判断是否存在这个员工，并且密码匹配
        if(u != null && passwordEncoder.matches(user.getPasswordHash(), u.getPasswordHash())){
            log.info("用户登录成功：{}", u.getUsername());

            //3.生成JWT令牌
            String jwt = jwtUtil.generateToken(u.getUsername(), u.getId(), u.getRoleName());

            return new LoginInfo(u.getId(),u.getUsername(),u.getRealName(),jwt);
        }

        //3.不存在或密码错误，返回null
        return null;
    }

    @Override
    public IPage<User> getUserPage(Integer currentPage, Integer pageSize, User user) {
        // 创建分页对象
        Page<User> page = new Page<>(currentPage, pageSize);

        // 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        if (StringUtils.hasText(user.getUsername())) {
            queryWrapper.like("username", user.getUsername());
        }
        if (StringUtils.hasText(user.getRealName())) {
            queryWrapper.like("real_name", user.getRealName());
        }
        if (StringUtils.hasText(user.getClassName())) {
            queryWrapper.like("class_name", user.getClassName());
        }
        if (StringUtils.hasText(user.getCollege())) {
            queryWrapper.like("college", user.getCollege());
        }
        if (user.getRoleId() != null) {
            queryWrapper.eq("role_id", user.getRoleId());
        }
        if (user.getIsActive() != null) {
            queryWrapper.eq("is_active", user.getIsActive());
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("created_at");

        return this.page(page, queryWrapper);
    }

    @Override
    @Cacheable(value = "users", key = "'user:' + #userId", unless = "#result == null")
    public User getUserById(Long userId) {
        return userMapper.findByIdWithRole(userId);
    }

    @Override
    @CacheEvict(value = "users", key = "'user:' + #user.id")
    public boolean updateUser(User user) {
        // 设置更新时间
        user.setUpdatedAt(LocalDateTime.now());

        // 如果密码有更新，需要加密
        if (StringUtils.hasText(user.getPasswordHash()) && !user.getPasswordHash().startsWith("$2a$")) {
            user.setPasswordHash(passwordEncoder.encode(user.getPasswordHash()));
        }

        return this.updateById(user);
    }

    @Override
    @CacheEvict(value = "users", key = "'user:' + #userId")
    public boolean deleteUser(Long userId) {
        User user = new User();
        user.setId(userId);
        user.setDeleted(1);
        user.setUpdatedAt(LocalDateTime.now());
        return this.updateById(user);
    }

    @Override
    @Transactional
    @CacheEvict(value = "users", allEntries = true)
    public boolean batchDeleteUsers(List<Long> userIds) {
        List<User> users = userIds.stream().map(userId -> {
            User user = new User();
            user.setId(userId);
            user.setDeleted(1);
            user.setUpdatedAt(LocalDateTime.now());
            return user;
        }).collect(Collectors.toList());

        return this.updateBatchById(users);
    }

    @Override
    @CacheEvict(value = "users", key = "'user:' + #userId")
    public boolean updateUserStatus(Long userId, Boolean isActive) {
        User user = new User();
        user.setId(userId);
        user.setIsActive(isActive);
        user.setUpdatedAt(LocalDateTime.now());
        return this.updateById(user);
    }

    @Override
    @CacheEvict(value = "users", key = "'user:' + #userId")
    public boolean resetPassword(Long userId, String newPassword) {
        User user = new User();
        user.setId(userId);
        user.setPasswordHash(passwordEncoder.encode(newPassword));
        user.setUpdatedAt(LocalDateTime.now());
        return this.updateById(user);
    }

    @Override
    public boolean checkUsernameExists(String username) {
        return userMapper.countByUsername(username) > 0;
    }

    @Override
    @Transactional
    public int batchImportUsers(List<User> users) {
        int successCount = 0;
        LocalDateTime now = LocalDateTime.now();

        for (User user : users) {
            try {
                // 检查用户名是否已存在
                if (!checkUsernameExists(user.getUsername())) {
                    // 密码加密
                    user.setPasswordHash(passwordEncoder.encode(user.getPasswordHash()));
                    user.setIsActive(true);
                    user.setRoleId(4); // 默认为学生角色
                    user.setCreatedAt(now);
                    user.setUpdatedAt(now);

                    if (this.save(user)) {
                        successCount++;
                    }
                }
            } catch (Exception e) {
                log.error("导入用户失败：{}", user.getUsername(), e);
            }
        }

        return successCount;
    }

    @Override
    @Cacheable(value = "users", key = "'role:' + #roleId", unless = "#result == null || #result.isEmpty()")
    public List<User> getUsersByRoleId(Integer roleId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("created_at");
        return this.list(queryWrapper);
    }

    @Override
    public IPage<UserDTO> getUserPageWithRole(Page<UserDTO> page, String realName, Integer roleId, Boolean isActive, String college) {
        // 使用优化的JOIN查询，避免N+1问题
        return userMapper.selectUserPageWithRole(page, realName, roleId, isActive, college);
    }

    @Override
    public IPage<UserDTO> searchUsersByRealName(Page<UserDTO> page, String realName) {
        // 使用优化的索引查询
        return userMapper.selectUsersByRealName(page, realName);
    }

    @Override
    @Cacheable(value = "users", key = "'userDetails:' + #userId", unless = "#result == null")
    public UserDTO getUserDetailsById(Long userId) {
        // 使用优化的JOIN查询，避免N+1问题
        return userMapper.selectUserByIdWithRole(userId);
    }
}
